package dkbta;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import dkbta.processing.PlanException;

public class TaskServer {

	/**
	 * @param args
	 */
	private static final String CONFIG_FILE_NAME = "TaskServerConfig.xml";
	
	public static void main(String[] args) throws Throwable{
		
		Element	taskServerPlan = readDOMDocFromXML(new File(CONFIG_FILE_NAME)).getDocumentElement();
		Element serverElement = getXmlElement(taskServerPlan, "Config");
		String xmlFileName = serverElement.getAttribute("fileName");
		int port = new Integer(serverElement.getAttribute("port")).intValue();
		
		FileInputStream fstream = new FileInputStream(xmlFileName);
		DataInputStream in = new DataInputStream(fstream);
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String strLine;
		ServerSocket srv = new ServerSocket(port);
		System.out.println("Task Server started working");
		Socket socket = srv.accept();
		while ((strLine = br.readLine()) != null)   {
			socket.getOutputStream().write((strLine+"\n").getBytes());
		}
		System.out.println("Task Server finished working");
		socket.close();
		srv.close();
		
	}
	
	private static Document readDOMDocFromXML(File xml) throws Exception{
		// Create a builder factory
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setValidating(false);

		// Create the builder and parse the file
		return factory.newDocumentBuilder().parse(xml);
	}
	
	private static Element getXmlElement(Element parent, String tagName) throws PlanException{
		
		NodeList nodes = parent.getElementsByTagName(tagName);
		if (nodes.getLength() == 0){
			return null;
		}
		if (nodes.getLength() != 1){
			throw new PlanException("Multile '" + tagName + "' elements");
		}
		
		return (Element)nodes.item(0);
		}

}
